package com.mobileseed.weather;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mobile.weather.R;
import com.mobileseed.weather.data.HttpClientConnector;
import com.mobileseed.weather.data.Weather;
import com.mobileseed.weather.data.WeatherStringParse;
import com.mobileseed.weather.util.config;
import com.mobileseed.weather.util.unit;
import com.mobileseed.weather.util.CityLocator;

public class MobileWeatherActivity extends Activity {
    /** Called when the activity is first created. */
	private TextView conditionTextView;
	
	protected static final int MENU_SETOPTIONS = Menu.FIRST;
	protected static final int MENU_ABOUT = Menu.FIRST + 1;
	protected static final int MENU_EXIT = Menu.FIRST + 2;
	
	private static final int USER_MSG_BASE = 0x100;			//用户消息起始
	private static final int MSG_REFRESH_WEATHER = USER_MSG_BASE + 1;		//成功获取气象信息
	private static final int MSG_NETWORK_ERROR = USER_MSG_BASE + 2;			//网络出现错误
	
	private static final int APP_DATA_UPDATE_CIRCLE = 60*60*1000;			//程序默认1小时更新一次数据
	private static final int APP_MAX_ERROR_COUNT = 3;						//定义最大出错次数
	
	private boolean _bIsAppActive = true;									//程序是否互动
	private Handler _hdlMessageHandler = null;								//消息处理
	private CityLocator _cityLocator = null;								//位置获取
	
	//本地变量
	private String _strCurSelCityPY = null;			//当前城市拼音
	private String _strCurSelCityName = null;			//当前城市名
	private Weather _weather = null;				//当前气象信息
	private int _nErroCount = 0;					//记录出错次数
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //可以根据横批竖屏来设置背景
        LinearLayout global_layout = (LinearLayout)findViewById(R.id.global_layout);
        global_layout.setBackgroundResource(R.drawable.background_2);
        
        //中文加粗
        conditionTextView = (TextView)findViewById(R.id.condition);
        conditionTextView.getPaint().setFakeBoldText(true);  
        
        //获取当前城市设置
        LoadStoredPrefers();
        
        //创建消息处理
        CreateMessageHandler();
        
        //开始气象线程
        StartWeatherWorkingThread();
        
        //修改 背景色
        /*Resources res = getResources();
        Drawable drawable = res.getDrawable(R.drawable.bkcolor);
        this.getWindow().setBackgroundDrawable(drawable);*/ 
    }
    
    private Weather getCurrentDayWeather(String city){
    	String prifixUrl = "http://www.google.com/ig/api?hl=zh-cn&ie=utf-8&weather=";
    	String googleWeatherUrl = prifixUrl + city;
        String googleWeatherString = HttpClientConnector.getStringByUrl(googleWeatherUrl);
        return WeatherStringParse.parse(googleWeatherString);    
    }
    
    private void SetInterfaceData(Weather weather){
    	//设置日期
    	TextView forecasDateTextView = (TextView)findViewById(R.id.forecastDate);
    	forecasDateTextView.setText(weather.getInformation().getForecastDate());
    	//设置星期
    	TextView dayOfWeekTextView = (TextView)findViewById(R.id.dayOfWeek);
    	dayOfWeekTextView.setText(((weather.getConditions())[0]).getDayOfWeek());
    	//设置当前天气数据
    	TextView realTempCTextView = (TextView)findViewById(R.id.realTempC);
    	realTempCTextView.setText(weather.getCurrentConditions().getTempC() + unit.DEGREE_CELSIUS + " " + _strCurSelCityName);
    	TextView lowToHighTempCTextView = (TextView)findViewById(R.id.lowToHighTempC);
    	lowToHighTempCTextView.setText(weather.getConditions()[0].getLow() + " ~ " + weather.getConditions()[0].getHigh());
    	TextView conditionTextView = (TextView)findViewById(R.id.condition);
    	conditionTextView.setText(weather.getCurrentConditions().getCondition());
    	ImageView currentImageView = (ImageView)findViewById(R.id.currentWeatherImage);
    	currentImageView.setImageDrawable(weather.getCurrentConditions().getIconDrawable());
    	//当前天气湿度设置
    	TextView humidityTextView = (TextView)findViewById(R.id.humidity);
    	String humidity = weather.getCurrentConditions().getHumidity();
    	Log.i("HUMIDITY", humidity);
    	Pattern pattern = Pattern.compile("\\d+%$");
		Matcher matcher = pattern.matcher(humidity);
		if (matcher.find()) {
			Log.i("matcher", matcher.group());
			humidityTextView.setText(matcher.group());
		}		
    	//设置未来四天的预测数据
    	//第一天
    	TextView firstDayOfWeekTextView = (TextView)findViewById(R.id.firstDayOfWeek);
    	firstDayOfWeekTextView.setText(weather.getConditions()[0].getDayOfWeek());
    	TextView firstLowTempCTextView = (TextView)findViewById(R.id.firstLowTempC);
    	firstLowTempCTextView.setText(weather.getConditions()[0].getLow());
    	TextView firstHighTempCTextView = (TextView)findViewById(R.id.firstHighTempC);
    	firstHighTempCTextView.setText(weather.getConditions()[0].getHigh());
    	ImageView firstWeatherImageView = (ImageView)findViewById(R.id.firstWeatherImage);
    	firstWeatherImageView.setImageDrawable(weather.getConditions()[0].getIconDrawable());
    	
    	//第二天
    	TextView secondDayOfWeekTextView = (TextView)findViewById(R.id.secondDayOfWeek);
    	secondDayOfWeekTextView.setText(weather.getConditions()[1].getDayOfWeek());
    	TextView secondLowTempCTextView = (TextView)findViewById(R.id.secondLowTempC);
    	secondLowTempCTextView.setText(weather.getConditions()[1].getLow());
    	TextView secondHighTempCTextView = (TextView)findViewById(R.id.secondHighTempC);
    	secondHighTempCTextView.setText(weather.getConditions()[1].getHigh());
    	ImageView secondWeatherImageView = (ImageView)findViewById(R.id.secondWeatherImage);
    	secondWeatherImageView.setImageDrawable(weather.getConditions()[1].getIconDrawable());
    	//第三天
    	TextView thirdDayOfWeekTextView = (TextView)findViewById(R.id.thirdDayOfWeek);
    	thirdDayOfWeekTextView.setText(weather.getConditions()[2].getDayOfWeek());
    	TextView thirdLowTempCTextView = (TextView)findViewById(R.id.thirdLowTempC);
    	thirdLowTempCTextView.setText(weather.getConditions()[2].getLow());
    	TextView thirdHighTempCTextView = (TextView)findViewById(R.id.thirdHighTempC);
    	thirdHighTempCTextView.setText(weather.getConditions()[2].getHigh());
    	ImageView thirdWeatherImageView = (ImageView)findViewById(R.id.thirdWeatherImage);
    	thirdWeatherImageView.setImageDrawable(weather.getConditions()[2].getIconDrawable());
    	//第四天
    	TextView fourthDayOfWeekTextView = (TextView)findViewById(R.id.fourthDayOfWeek);
    	fourthDayOfWeekTextView.setText(weather.getConditions()[3].getDayOfWeek());
    	TextView fourthLowTempCTextView = (TextView)findViewById(R.id.fourthLowTempC);
    	fourthLowTempCTextView.setText(weather.getConditions()[3].getLow());
    	TextView fourthHighTempCTextView = (TextView)findViewById(R.id.fourthHighTempC);
    	fourthHighTempCTextView.setText(weather.getConditions()[3].getHigh());
    	ImageView fourthWeatherImageView = (ImageView)findViewById(R.id.fourthWeatherImage);
    	fourthWeatherImageView.setImageDrawable(weather.getConditions()[3].getIconDrawable());
    }
    
    /*
     * 加载存储的设置
     */
    private void LoadStoredPrefers() {
    	
    	SharedPreferences settings = getSharedPreferences(config.PREF_NAME, MODE_WORLD_READABLE);
    	
    	//尝试获取用户存储值
    	_strCurSelCityPY = settings.getString(config.PREF_SEL_CITYPY, "");
    	_strCurSelCityName = settings.getString(config.PREF_SEL_CITYNAME, "");
    	
    	//如果未存储，则选择定位值
    	if(_strCurSelCityPY.equals(""))
    	{
    		_strCurSelCityPY = settings.getString(config.PREF_GPS_CITYPY, "");
    		
    		//同时开启线程尝试获取新的当前位置
	    	_cityLocator = new CityLocator(MobileWeatherActivity.this);
	    	_cityLocator.start();
    	}
    }
    
    /*
     * 创建消息处理
     */
    private void CreateMessageHandler() {
    	
    	//处理子线程发送来的消息
    	_hdlMessageHandler = new Handler() {
    		
			@Override
			public void handleMessage(Message msg) {
				
				switch(msg.what) {
				case MSG_REFRESH_WEATHER:			//成功获取气象信息
					
					//根据气象信息更新界面
					SetInterfaceData(_weather);
					break;
					
				case MSG_NETWORK_ERROR:				//出现网络错误
					
					//提示用户
					Toast.makeText(getApplicationContext(), getString(R.string.error_toast_msg), Toast.LENGTH_LONG).show();
					break;
				}
				
				super.handleMessage(msg);
			}
    		
    	};
    }
    
    /*
     * 启动后台的数据处理线程
     */
    private void StartWeatherWorkingThread() {
    	    	
    	//气象信息获取线程
    	new Thread(new Runnable() {
    		
    		@Override
    		public void run() {
    			//程序活动时更新
    			while(_bIsAppActive) {
    				try {
    					//直到获取到当前城市为止
    					while(_strCurSelCityPY == null || _strCurSelCityPY.equals("")) {
							
    						//等待200毫秒后重试
    						if(_cityLocator != null) {
    							_strCurSelCityPY = _cityLocator.getCity();
    						}
    						
    						Thread.sleep(200);
    					}
    					
    					//获取到城市名，开始获取天气信息
    					_weather = getCurrentDayWeather(_strCurSelCityPY);
    					
    					boolean bGotWBSuccess = true;
    					
    					//如果未成功获取则继续
    					if(_weather == null) {
    						
    						_nErroCount++;
    						
    						//检查是否到达出错上限
    						if(_nErroCount >= APP_MAX_ERROR_COUNT)
    						{
    							bGotWBSuccess = false;
    						}
    						else
    						{
    							continue;
    						}
    					}
    					
    					//成功获取信息，通知主界面更新数据
    					Message msg = new Message();
                        msg.obj = null;
                        
                        if(bGotWBSuccess) 
                        {
                        	msg.what = MSG_REFRESH_WEATHER;
                        }
                        else
                        {
                        	msg.what = MSG_NETWORK_ERROR;
                        }
                        
                        _hdlMessageHandler.sendMessage(msg);
    					
    					Thread.sleep(APP_DATA_UPDATE_CIRCLE);
    				} catch(InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}).start();
    }
    
    /*
     * 相应Menu命令
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	menu.add(0, MENU_SETOPTIONS, 0, getString(R.string.menu_option));
    	menu.add(0, MENU_ABOUT, 0, getString(R.string.menu_about));
    	menu.add(0, MENU_EXIT, 0, getString(R.string.menu_exit));
    	
    	return true;
    }

    /*
     * 相应选中某Menu项目命令
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()) {
		
		case MENU_SETOPTIONS:		//跳转到设置界面
			Intent optintent = new Intent();
			optintent.setClass(MobileWeatherActivity.this, WeatherOptionActivity.class);
			startActivity(optintent);
			
			break;
			
		case MENU_ABOUT:		//关于
			
			break;
			
		case MENU_EXIT:			//退出
			
			this.finish();
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
}